<template>
  <div class="plan-board-detail">
    <a-card>
      <title-name>
        <div class="title-wrapper">
          <span v-if="businessType === '0'">上月逾期未完成节点</span>
          <span v-else-if="businessType === '1'">本月计划</span>
          <span v-else-if="businessType === '2'">下月重点计划</span>
          <template>
            <span class="tips">父级阶段类别的完成状态请在“树状视图”下设置</span>
            <a-button
              type="primary"
              icon="unordered-list"
              :ghost="!viewMode"
              :disabled="loading"
              @click="viewMode = true"
            >
              平铺视图
            </a-button>
            <a-button
              type="primary"
              :ghost="viewMode"
              :disabled="loading"
              @click="viewMode = false"
            >
              <BaseSvgIcon
                class="icon-item"
                icon="tree"
              />
              树状视图
            </a-button>
          </template>
        </div>
      </title-name>
      <div v-if="!viewMode" class="btn-wrapper">
        <a-button
          type="primary"
          :disabled="loading"
          @click="$refs.table.setAllTreeExpansion()"
        >
          展开全部
        </a-button>
        <a-button
          type="primary"
          :disabled="loading"
          @click="$refs.table.clearTreeExpand()"
        >
          收起全部
        </a-button>
        <a-button
          type="primary"
          :disabled="loading"
          @click="loadData"
        >
          手动刷新
        </a-button>
      </div>
      <div class="pub-table-select-count">
        <a-icon
          type="info-circle"
          theme="twoTone"
        />
        <span>
          项目：<span class="totalNum">{{ projectName }}</span>
        </span>
        <span>
          节点共 <span class="totalNum">{{ tableInfo.nodeCount }}</span> 项
        </span>
        <span>
          一级节点共 <span class="totalNum">{{ tableInfo.oneNodeCount }}</span> 项
        </span>
        <span>
          二级节点共 <span class="totalNum">{{ tableInfo.twoNodeCount }}</span> 项
        </span>
        <span>
          三级节点共 <span class="totalNum">{{ tableInfo.threeNodeCount }}</span> 项
        </span>
        <span>
          周期天数 <span class="totalNum">{{ tableInfo.durationCount }}</span> 天
        </span>
        <span>
          周期间隔 <span class="totalNum">{{ tableInfo.cycleInterval }}</span>
        </span>
      </div>
      <!-- 搜索 -->
      <a-form-model
        :model="searchForm"
        layout="inline"
        class="plan-board-detail-search"
      >
        <a-form-model-item>
          <b>搜索:</b>
        </a-form-model-item>
        <a-form-model-item>
          <a-input
            v-model="searchForm.businessMatters"
            placeholder="节点名称"
            class="plan-board-detail-search-width"
          />
        </a-form-model-item>
        <a-form-model-item>
          <a-select
            v-model="searchForm.controlLevel"
            placeholder="节点管控级别"
            class="plan-board-detail-search-width"
            allowClear
          >
            <a-select-option
              v-for="item in controlLevelList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-range-picker
            v-model="searchForm.planStart"
            class="plan-board-detail-search-date"
            :placeholder="['计划开始时间起','计划开始时间止']"
          />
        </a-form-model-item>
        <a-form-model-item>
          <a-range-picker
            v-model="searchForm.planEnd"
            class="plan-board-detail-search-date"
            :placeholder="['计划完成时间起','计划完成时间止']"
          />
        </a-form-model-item>
        <a-form-model-item>
          <a-range-picker
            v-model="searchForm.completeDate"
            class="plan-board-detail-search-date"
            :placeholder="['实际完成时间起','实际完成时间止']"
          />
        </a-form-model-item>
        <a-form-model-item>
          <a-select
            v-model="searchForm.reviewStatus"
            placeholder="复核状态"
            class="plan-board-detail-search-width"
            allowClear
          >
            <a-select-option
              v-for="item in reviewStatusList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-input
            v-model="searchForm.reviewPerName"
            placeholder="复核人名称"
            class="plan-board-detail-search-width"
          />
        </a-form-model-item>
        <a-form-model-item>
          <a-select
            v-model="searchForm.status"
            placeholder="节点状态"
            class="plan-board-detail-search-width"
            allowClear
          >
            <a-select-option
              v-for="item in nodeStatusList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button
            type="primary"
            :loading="loading"
            @click="loadData(true)"
          >
            搜索
          </a-button>
          <a-button
            :disabled="loading"
            class="ml12"
            @click="handleReset"
          >
            重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
      <!-- 搜索 -->
      <a-spin :spinning="loading">
        <u-table
          ref="table"
          fixed-columns-roll
          :height="500"
          show-header-overflow
          :tree-config="{
            children: 'children',
            expandAll: false,
          }"
          row-id="id"
          :use-virtual="true"
          border
        >
          <u-table-column
            v-for="item in columns"
            :key="item.dataIndex"
            :prop="item.dataIndex"
            :label="item.title"
            :width="item.width"
            :tree-node="item.dataIndex === 'name'"
            align="center"
          >
            <template v-slot="{ row }">
              <span
                :title="row[item.dataIndex]"
                class="span-ellipsis"
              >
                <template v-if="row.type === 0">
                  <template v-if="['sortNum', 'statusName', 'name','businessMatters','duration','startDate','endDate'].includes(item.dataIndex)">
                    {{ row[item.dataIndex] }}
                  </template>
                  <template v-else-if="item.dataIndex === 'controlLevel'">
                    {{ row.controlLevelName }}
                  </template>
                  <template v-else-if="item.dataIndex === 'reviewPerName'">
                    {{ row.reviewPerName || '-' }}
                  </template>
                  <template v-else-if="item.dataIndex === 'reviewStatusName'">
                    <a
                      v-if="row.reviewStatusName && row.reviewStatusName !== '-'"
                      @click="handleNodeReviewRecord(row)"
                    >{{ row.reviewStatusName }}</a>
                    <span v-else>-</span>
                  </template>
                </template>
                <template v-else>
                  <span
                    v-if="item.dataIndex === 'sortNum'"
                    :class="indexClass(row)"
                    class="sort-num"
                  >
                    <img
                      v-if="row.promptLights === 1 || row.promptLights === 2"
                      :src="row.promptLights === 1 ? yellowLight : redLight"
                      width="20"
                      hight="20"
                    >
                    <span>{{ row[item.dataIndex] }}</span>
                  </span>
                  <template v-else-if="item.dataIndex === 'controlLevel'">
                    {{ row.controlLevelName }}
                  </template>
                  <template v-else-if="item.dataIndex === 'reviewPerName'">
                    {{ row.reviewPerName || '-' }}
                  </template>
                  <template v-else-if="item.dataIndex === 'reviewStatusName'">
                    <a
                      v-if="row.reviewStatusName && row.reviewStatusName !== '-'"
                      @click="handleNodeReviewRecord(row)"
                    >{{ row.reviewStatusName }}</a>
                    <span v-else>-</span>
                  </template>
                  <template v-else-if="item.dataIndex === 'directResPerList'">
                    {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                  </template>
                  <template v-else>
                    {{ row[item.dataIndex] }}
                  </template>
                </template>
              </span>
            </template>
          </u-table-column>
          <u-table-column
            key="operation"
            prop="operation"
            label="操作"
            width="200"
            align="center"
            :fixed="'right'"
          >
            <template v-slot="{ row }">
              <!-- 状态（1：审核中/2：按期完成/3：逾期完成/4：审核不通过/5：全部完成/6：未全部完成/7:待开始/8:进行中 9预期未完成 10 未全部完成（最后一个节点） -->
              <MoreButton :key="row.id + new Date().getTime()">
                <a
                  v-if="row.type === 1"
                  v-btnPermission="'pm_068_loo_01'"
                  @click="handleNodeMaintain(row, 'detail')"
                >查看</a>
                <a
                  v-if="row.type === 1 && (row.status === 2 || row.status === 3)"
                  v-btnPermission="'pm_068_fuh_08'"
                  @click="handleNodeReview(row)"
                >复核</a>
                <a
                  v-if="row.type === 1 && (row.status === 4 || row.status === 7 || row.status === 8 || row.status === 9)"
                  v-btnPermission="'pm_068_fin_06'"
                  @click="handleNodeMaintain(row,'update')"
                >节点完成</a>
                <!--  -->
                <a
                  v-if="row.status === 10"
                  v-btnPermission="'pm_068_ffi_07'"
                  @click="handleCompleteShow(row)"
                >设置完成情况</a>
                <a
                  v-if="row.type === 1 && (row.status === 1 || row.status === 2 || row.status === 3)"
                  @click="handleApproveDetail(row)"
                >审批信息</a>
              </MoreButton>
            </template>
          </u-table-column>
        </u-table>
      </a-spin>
    </a-card>
    <!-- 节点完成 -->
    <NodeMaintain
      :visible.sync="nodeMaintainVisible"
      :data="data"
      @refresh="refresh"
    />
    <!-- 节点完成 -->
    <!-- 自定义审批信息 -->
    <ApprovalDetail
      :title="'审批信息'"
      :business-id="businessId"
      :visible="visibleApprove"
      @cancel="visibleApprove = false"
      @confirm="visibleApprove = false"
    />
    <!-- 自定义审批信息 -->
    <!-- 设置完成情况 -->
    <BaseModal
      :visible="setCompleteModal.visible"
      title="阶段/类别完成情况"
      :width="1200"
      destroy-on-close
      @cancel="setCompleteModal.visible = false"
    >
    <div>
      <a-form-model :model="setCompleteModal">
          <a-form-model-item style="margin-bottom: 0;">
            <span style="color: red;margin-bottom: 0;">若选择是，则该父级节点不再生成至下月计划中。</span>
          </a-form-model-item>
          <a-form-model-item>
            <span>“{{ setCompleteModal.name }}”是否全部完成：</span>
            <a-switch v-model="setCompleteModal.isComplete" checked-children="是" un-checked-children="否"></a-switch>
          </a-form-model-item>
      </a-form-model>
    </div>
    <template slot="footer">
      <a-button @click="setCompleteModal.visible = false">
        取消
      </a-button>
      <a-button
        type="primary"
        :loading="setCompleteModal.loading"
        @click="handleNodeComplete"
      >
        确定
      </a-button>
    </template>
  </BaseModal>
  <!-- 设置完成情况 -->
   <!-- 复核 -->
   <NodeReview :visible.sync="nodeReviewVisible" type="0" :nodeId="nodeReviewId" @submit="handleNodeReviewSubmit"></NodeReview>
    <!--复核 -->
    <!-- 复核记录-->
    <NodeReviewRecord :visible.sync="nodeReviewRecordVisble" :nodeId="nodeReviewId"></NodeReviewRecord>
    <!--复核记录 -->
  </div>
</template>
<script>
import { columnsDetail, controlLevelList, nodeStatusList, reviewStatusList } from '../model.js'
import BaseModal from '@/components/BaseModal'
import NodeReview from '@/views/construction/components/NodeReview'
import NodeReviewRecord from '@/views/construction/components/NodeReviewRecord'
import monthPlanApi from '@/api/construction/monthPlanApi'
import { UTable, UTableColumn } from 'umy-ui'
import NodeMaintain from './NodeMaintain'
import ApprovalDetail from './ApprovalDetail'
export default {
  name: 'PlanBoardDetail',
  props: {
    businessType: {
      type: String,
      default: ''
    },
    allData: {
      type: Object,
      default: () => {}
    },
  },
  components: {
    UTable,
    BaseModal,
    UTableColumn,
    NodeMaintain,
    ApprovalDetail,
    NodeReview,
    NodeReviewRecord,
  },
  data() {
    return {
      //节点复核
      nodeReviewVisible:false,
      // 节点 id
      nodeReviewId: '',
      //复核记录
      nodeReviewRecordVisble:false,
      projectName: '',
      // 加载
      loading: false,
      // 设置完成
      setCompleteModal: {
        loading: false,
        visible: false,
        isComplete: false,
        name: '',
        id: ''
      },
      // 表格信息
      tableInfo: {
        nodeCount: 0,
        oneNodeCount: 0,
        twoNodeCount: 0,
        threeNodeCount: 0,
        durationCount: 0,
        cycleInterval: 0
      },
      columnsOther: [
        {
          title: '复核情况',
          width: 150,
          dataIndex: 'reviewStatusName',
        },
        {
          title: '复核人',
          width: 120,
          dataIndex: 'reviewPerName'
        },
        {
          title: '状态',
          width: 150,
          dataIndex: 'statusName'
        },
      ],
      // 红灯
      redLight: require('@/assets/icons/redLight.png'),
      // 黄灯
      yellowLight: require('@/assets/icons/yellowLight.png'),
      // 表格数据
      tableData: [],
      // 搜索表单
      searchForm: {},
      // 是否搜索
      isSearch: false,
      // 节点管控级别列表
      controlLevelList,
      // 节点状态列表
      nodeStatusList,
      // 复核状态列表
      reviewStatusList,
      // 节点完成显示隐藏
      nodeMaintainVisible: false,
      // 节点完数据
      data: {},
      // 审批信息隐藏显示
      visibleApprove: false,
      // 业务id
      businessId: void 0,
      // 视图模式,true:平铺视图,false:树状视图
      viewMode: true
    }
  },
  computed: {
    columns() {
      let list = this.$clone(columnsDetail)
      list.splice(7, 0, {
        title: '实际完成时间',
        width: 150,
        dataIndex: 'completeDate'
      })
      list = list.concat(this.columnsOther)
      return list
    }
  },
  watch: {
    viewMode: {
      handler() {
        this.loadData()
      }
    },
    // 监听视图模式改变重新加载数据
      allData: {
        handler(val) {
          if (val) {
            if (this.viewMode) {
              this.tableData = val.nodes ? val.nodes : []
            } else {
              this.tableData = val.tree ? val.tree : []
            }
            this.tableInfo = {
              nodeCount: val.nodeCount || 0, // 节点总数
              oneNodeCount: val.oneNodeCount || 0, // 一级节点
              twoNodeCount: val.twoNodeCount || 0, // 二级节点
              threeNodeCount: val.threeNodeCount || 0, // 三级节点
              durationCount: val.durationCount || 0, // 周天总数
              cycleInterval: val.cycleInterval || 0, // 周期间隔
            }
          }
          
        }
      },
    // 表格数据监听
    tableData: {
      handler(list) {
        if (this.$refs.table) {
          // 获取之前展开数据
          const expandRecords = this.$refs.table.getTreeExpandRecords()
          // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
          const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
          const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
          // 加载数据
          this.$refs.table.reloadData(list).then(() => {
            // 是搜索默认展开全部
            if (this.isSearch) {
              this.$refs.table.setAllTreeExpansion()
              this.isSearch = false
            } else {
              // 数据加载完成出现之后，打开之前的展开行
              expandRecords.forEach((row) => {
                this.$refs.table.setTreeExpansion(row, true)
              })
            }
            try {
              // 还原之前滚动高度
              this.$refs.table.pagingScrollTopLeft(scrollTop + 1, scrollLeft)
              this.$nextTick(()=>{
                // 不加这一步，列表操作栏 会变形
                this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
              })
            } catch (e) {
              console.log(e)
            }
            
          })
        }
      }
    }
  },
  async mounted() {
    this.projectName = this.$route.query.projectName || ''
  },
  methods: {
    /**
     * @description: 刷新
     * @return {void}
     */
    refresh(){
      this.loadData()
      this.$emit('synchronousUpdate')
    },
    /**
     * @description: 表格数据加载方法
     * @param {boolean} isSearch 是否搜索
     * @return {Promise} 接口Promise
     */
    async loadData(isSearch = false) {
      try {
        this.loading = true
        if (isSearch) {
          this.isSearch = isSearch
        }
        let fun = monthPlanApi.getNodeTree
        const {
          code,
          data
        } = await fun(this.getSearchParms())
        if (code === 200) {
          const resp = data[this.businessType]
          this.tableInfo = {
            nodeCount: resp.nodeCount || 0, // 节点总数
            oneNodeCount: resp.oneNodeCount || 0, // 一级节点
            twoNodeCount: resp.twoNodeCount || 0, // 二级节点
            threeNodeCount: resp.threeNodeCount || 0, // 三级节点
            durationCount: resp.durationCount || 0, // 周天总数
            cycleInterval: resp.cycleInterval || 0, // 周期间隔
          }
          if (this.viewMode) {
            this.tableData = resp.nodes ? resp.nodes : []
          } else {
            this.tableData = resp.tree ? resp.tree : []
          }
        } else {
          this.tableData = []
        }
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      } finally {
        this.loading = false
      }
    },
    /**
     * @description: 刷新
     * @return {void}
     */
    handleRefresh() {
      this.loadData()
    },
    /**
     * @description: 获取搜索参数
     * @return {Object}
     */
    getSearchParms() {
      let startDateStart = void 0,
        startDateEnd = void 0,
        endDateStart = void 0,
        endDateEnd = void 0,
        completeDateStart = void 0,
        completeDateEnd = void 0
      if (Array.isArray(this.searchForm?.planStart) && this.searchForm.planStart.length>0) {
        startDateStart = this.searchForm.planStart[0].format('YYYY-MM-DD')
        startDateEnd = this.searchForm.planStart[1].format('YYYY-MM-DD')
      }
      if (Array.isArray(this.searchForm?.planEnd) && this.searchForm.planEnd.length>0) {
        endDateStart = this.searchForm.planEnd[0].format('YYYY-MM-DD')
        endDateEnd = this.searchForm.planEnd[1].format('YYYY-MM-DD')
      }
      if (Array.isArray(this.searchForm?.completeDate) && this.searchForm.completeDate.length>0) {
        completeDateStart = this.searchForm.completeDate[0].format('YYYY-MM-DD')
        completeDateEnd = this.searchForm.completeDate[1].format('YYYY-MM-DD')
      }
      const { businessMatters, controlLevel, status, reviewStatus, reviewPerName } = this.searchForm
      return {
        businessType: this.businessType,
        rootId: this.$route.query.rootId,
        lookType: this.viewMode ? 1 : 0,
        businessMatters,
        controlLevel,
        startDateStart,
        startDateEnd,
        endDateStart,
        endDateEnd,
        completeDateStart,
        completeDateEnd,
        reviewStatus,
        reviewPerName,
        status,
      }
    },
    /**
     * @description: 重置搜索
     * @return {void}
     */
    handleReset() {
      this.searchForm = {}
      this.loadData()
    },
    /**
     * @description: 审批详情
     * @param {object} row 行数据
     * @return {void}
     */    
    handleApproveDetail(row){
      this.visibleApprove = true
      this.businessId = row.id
    },
    /**
     * @description: 递归查找父级 获取父级名称
     */
      getParentName(parentId) {
      let tableData = this.$clone(this.tableData)
      let name = ''
      const deepFn = (data) => {
        for (let i = 0;i< data.length;i++) {
          let item = data[i]
          if (item.id === parentId) {
            name = item.name
            return false
          } else if (item.children) {
            deepFn(item.children)
          }
        }
      }
      deepFn(tableData)
      return name
    },
    /**
     * @description: 节点完成
     * @param {object} row 行数据
     * @param {string} type 按钮类型
     * @return {void}
     */
    handleNodeMaintain(row, type) {
      this.nodeMaintainVisible = true
      this.data = {
        id: row.id,
        status: row.status,
        type,
        parentName: row.parentMasterNodeName,
      }
    },
    handleCompleteShow(row) {
      this.setCompleteModal = {
        visible: true,
        loading: false,
        isComplete: false,
        name: row.name,
        id: row.id
      }
    },
    /**
     * @description: 设置完成
     */
    handleNodeComplete() {
      this.setCompleteModal.loading = true
      monthPlanApi.setComplete({id: this.setCompleteModal.id, isComplete: this.setCompleteModal.isComplete}).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功！')
          this.loadData()
        }
      }).finally(() => {
        this.setCompleteModal.visible = false
        this.setCompleteModal.loading = false
      })
    },
    /**
     * @description: 复核
     */
    handleNodeReview(row) {
      this.nodeReviewId = row.id
      this.nodeReviewVisible = true;
    },
    handleNodeReviewSubmit() {
      this.loadData()
    },
    // 复核记录
    handleNodeReviewRecord(row){
      this.nodeReviewId = row.id
      this.nodeReviewRecordVisble = true;
    },
    /**
     * @description: 索引类名
     * @param {object} row 行数据
     * @return {string}
     */    
    indexClass(row){
      return row.promptLights === 1 || row.promptLights === 2 ? '': 'class-' + row.statusLights
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.title-wrapper {
    display: flex;    
    .tips {
      color: red;
      font-size: 14px;
      margin-left: auto;
      line-height: 32px;
      font-weight: 300;
      margin-right: 6px;
    }
    > button {
      margin-left: 6px;
      &:first-of-type {
        margin-left: 0;
      }
    }
  }
.plan-board-detail {
  margin-top: 15px;
}
.btn-wrapper {
  margin: 0 -5px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  >button, >span, >div{
    margin: 5px;
  }
}
.pub-table-select-count {
  > span {
    margin-right: 12px;
  }
}
.sort-num {
  display: block;
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    margin-right: 5px;
    width: 16px;
    height: 16px;
  }
}
.class-0, .class-1, .class-2, .class-3, .class-4{
  color: #fff;
}
.class-0 {
  // background-color: #d1d1d1;
  color: #606266;
}
.class-1 {
  color: #606266;
}
.class-2 {
  background-color: #f85c62;
}
.class-3 {
  background-color: #1dc682;
}
.class-4 {
  background-color: #ffced0;
}

.plan-board-detail-search {
  margin-bottom: 10px;
  @{deep} .ant-form-item .ant-form-item-label {
    width: 0;
  }
  @{deep} .ant-form-item .ant-form-item-control-wrapper {
    width: 100%;
  }
}
.plan-board-detail-search-width {
  width: 200px;
}
.plan-board-detail-search-date{
  width: 268px;
}
.activity-on-arrow{
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-left: 5px;
}
</style>
